//index.js
const app = getApp()
var amapFile = require('../../lib/amap-wx.js');
var markersData = {
  latitude:'',
  longitude:'',
  key:"a53e2b35cf90ed37f1c97c99edf2cad2"
}


Page({
  data: {
    articles:[],
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    location:"",
  },
  getUserLocation:function(){
    if(app.globalData.location){
      this.setData({
        location:app.globalData.location
      })
    }else{
      console.log("获取定位中")
      var that = this;
      wx.getLocation({
        type: 'gcj02',
        success (res) {
          var latitude = res.latitude;
          var longtitude = res.longitude;
          console.log(res);
          that.loadCity(latitude,longtitude);
        },
      })
    }
  },
  loadCity:function(lat,lon){
    var that = this;
    var myAmapFunction = new amapFile.AMapWX({key:markersData.key});
    myAmapFunction.getRegeo({
      location:''+lon+','+lat+'',
      success: function(data){
        console.log(data);
        var location =
        data[0].regeocodeData.addressComponent.city;
        that.setData({
          location:location
        })
        app.globalData.location = location
      },
      fail:function(info){
        console.log(info);
      }
    })
  },
  onLoad: function() {
    this.setData({
      search: this.search.bind(this)
    })
    this.getUserLocation();
    wx.showLoading({
      title: '刷新中',
    })
    var that = this
    if (!wx.cloud) { 
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }
    //权限处理
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    
     this.onQuery(function(){
      wx.hideLoading({
        success: (res) => {},
      })
     })
  },



    // 事件处理函数
    go:function(e){
      var tapIndex = e.currentTarget.dataset.index;
      var article_str = JSON.stringify(this.data.articles[tapIndex]);
      wx.showLoading({
        title: '加载中',
      })
      wx.navigateTo({
        url: '../note/note?article='+article_str+'&&tapIndex='+tapIndex,
      })
      wx.hideLoading({
        success: (res) => {},
      })
    },

  onGetOpenid: function() {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },
  writeNote:function(){
    wx.showLoading({
      title:'加载中'
    })
    if(this.data.articles[0]){
      wx.navigateTo({
        url: '../writeNote/writeNote?currentID='+(parseInt(this.data.articles[0].id)+1),
      })
    }else{
      wx.navigateTo({
        url: '../writeNote/writeNote?currentID=1'
      })
    }
    wx.hideLoading({
      success: (res) => {},
    })
  },
    /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.onQuery(function(){})
    if(app.globalData.articles){
      this.setData({
        articles:app.globalData.articles
      })
    }
  },
  search: function (e,value) {
    //
    return new Promise((resolve, reject) => {
      if(e){
        const _this = this
        this.screenName = e
        const db = wx.cloud.database()
        const _ = db.command
        db.collection('articles').where(_.or([
         {
          title:db.RegExp({
            regexp:e,
            option:'i'
          })
         },
         {
          content:db.RegExp({
            regexp:e,
            option:'i'
          })
         },
         {
          location:db.RegExp({
            regexp:e,
            option:'i'
          })
         }
        ])).get({
          success: function(res) {
            var titles = []
            var  numsOfResult = res.data.length<=5?res.data.length:5;
            for(var i = 0 ;i < numsOfResult;i++){
              titles.push({
                text:res.data[i].title,
                value:i+1,
              })
            }
            resolve(titles)
          },
          fail:function(err){
            console.error(err)
          }
        })
      }
    })
  },
  onQuery: function(callback) {
    const db = wx.cloud.database()
    // 查询所有的文章
    db.collection('articles').where({}).get({
      success: res => {
        app.globalData.articles = res.data.reverse()
        this.setData({
          articles:app.globalData.articles
        },function(){
          callback()
        })
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading({
      title:'加载中'
    })
    this.onQuery(function(){});
    wx.hideLoading({
      success: (res) => {},
    })
  },
  onSearchResultClick(e){
    this.queryByValues(e.detail.item.text,function(){})
  },
  onSearchBarClear(e){
    console.log("clear")
  },
  queryByValues(values,callback){
    const db = wx.cloud.database()
    // 查询所有的文章
    db.collection('articles').where({title:values}).get({
      success: res => {
        app.globalData.articles = res.data.reverse()
        this.setData({
          articles:app.globalData.articles
        },function(){
          callback()
        })
        console.log('[数据库] [查询记录] 成功: ', res)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  }
})
